package com.topfinance.cnaps2.util;

import java.util.Map;
import org.apache.log4j.Logger;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;

import com.topfinance.cnaps2.ebo.SysUserEbo;
import com.topfinance.cnaps2.util.Constants;

@SuppressWarnings("serial")
public class AuthInterceptor extends MethodFilterInterceptor {

    private static Logger log = Logger.getLogger(AuthInterceptor.class);

    //private List<String> operations = new ArrayList<String>();

//    public void setOperations(String operationNames) {
//        if (log.isDebugEnabled()) {
//            log.debug("setOperations() - operations = " + operationNames);
//        }
//        String[] operationsArray = operationNames.split(",");
//        for (int i = 0; i < operationsArray.length; i++) {
//            operations.add(operationsArray[i].toLowerCase().trim());
//        }
//    }

    @SuppressWarnings("unchecked")
    public String doIntercept(ActionInvocation invocation) throws Exception {
        Map session = invocation.getInvocationContext().getSession();

        SysUserEbo userInfo = (SysUserEbo) session.get(Constants.SESSION_USER_EBO);
        log.debug("[doIntercept]" + userInfo);
        if (userInfo == null) {
//            // TBD cached access url
            return ActionSupport.LOGIN;
        }
        // check user operations
        //boolean hasPermission = false;
//        if (log.isDebugEnabled()) {
//            log.debug("intercept() - operations: " + ArrayUtils.toString(operations));
//        }
//        if (operations.isEmpty()) {
//            hasPermission = true;
//        } else {
//            List<String> userOperations = userInfo.getOperations();
//            for (String operation : userOperations) {
//                if (operations.contains(operation.toLowerCase())) {
//                    hasPermission = true;
//                    break;
//                }
//            }
//        }
        //if (hasPermission) {
        //    return invocation.invoke();
        //}
        String result = invocation.invoke();
        return result;
        //return String.valueOf(HttpServletResponse.SC_FORBIDDEN);
    }
}
